import React, { useEffect, useState } from 'react';
import moment from 'moment';
import { Button, Form, Input, message, Modal, Select, Tooltip } from 'antd';
import { HttpCode } from '#/utils/contacts.js';
// @ts-ignore
import { TRCheckboxModal } from '@/components/index.js';
// @ts-ignore
import { BellOutlined } from '#/utils/antdIcons';
import TRNotification from '#/utils/notification.js';
import { SetRemindersModal, ShowDatePicker, ShowTimePicker } from '../index';
import { editPendingH, savePendingH } from '../../service';
import type { ISearchFormData } from '../../type';
import { CHECKTIME, REMINDER_TYPE_LIST } from '../../dictionary';

import styles from './index.less';

// const TextArea = Input.TextArea;
interface IProps {
  /**
   * 是否是编辑状态
   */
  isEdit: boolean;

  onPress: (data: Record<string, any>) => void;
  /**
   * searchFormData
   */
  searchFormData: ISearchFormData;
  /**
   * 刷新key值
   */
  setFlashKey: (e: string | number) => void;
  setMonthflashKey: (e: number) => void;
  /**
   * 表单值
   */
  value?: any;
  /**
   * 刷新基础数据
   */
  getSearchFormData: () => void;
  /**
   * 按钮权限
   */
  buttonPermissions?: any;
}

const TodoModalComponent = (props: IProps) => {
  const {
    isEdit,
    onPress,
    searchFormData,
    setFlashKey,
    setMonthflashKey,
    value: _value,
    getSearchFormData,
    buttonPermissions,
    marketId,
  } = props;
  const [visible, setVisible] = useState<boolean>(true);
  const [value, setValue] = useState<any>({});

  const [warnText, setWarnText] = useState<string>('提醒设置');
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const { dealElementOptions, dealElementModalOptions, dealElementDataObj } = searchFormData;

  const [form] = Form.useForm();

  useEffect(() => {
    if (_value) {
      const data = {
        ..._value,
        id: _value?.id ? [_value?.id] : null,
        calendarDate: _value?.calendarDate ? moment(_value.calendarDate) : null,
        stationList: _value?.stationList
          ? _value?.stationList?.map((item: any) => item?.value)
          : [],
        pendingTime:
          _value?.pendingEndTime && _value?.pendingStartTime
            ? [moment(_value?.pendingStartTime), moment(_value?.pendingEndTime)]
            : [],
      };
      const reminderTypeData = REMINDER_TYPE_LIST.find(
        (item: any) => item.value === _value?.reminderType,
      );
      const text =
        (_value?.remindFlag === '1' && _value?.reminderTime && _value?.reminderTime.length > 0) ||
        reminderTypeData ||
        _value?.reminderList
          ? `提醒设置：${
              _value?.reminderTime && _value?.reminderTime.length > 0
                ? _value?.reminderTime
                    .map((item: any) => {
                      return CHECKTIME[String(item)]?.label;
                    })
                    .join(',')
                : '无'
            } / ${reminderTypeData ? reminderTypeData?.label : '无'} / 提醒对象(${
              _value?.reminderList ? _value?.reminderList?.length : 0
            }人)：${
              _value?.reminderList && _value?.reminderList?.length > 0
                ? _value?.reminderList.map((item: any) => item.name).join(',')
                : '无'
            }`
          : '提醒设置';
      setValue(data);
      setWarnText(text);
      form && form.setFieldsValue(data);
    }
  }, [searchFormData, _value]);

  // 取消按钮
  const _onCancel = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  // 点击交易单元弹出Modal框
  const handelSelectDealElement = async () => {
    let data = form.getFieldsValue()?.stationList || [];
    data = data.map((item: any) => dealElementDataObj[item]?.[0]?.value);
    const result = await TRCheckboxModal.show({
      treeData: dealElementModalOptions,
      value: data,
      title: '交易单元',
    });
    if (result.index === 1) {
      const checkedKeys = result?.checkedKeys?.map(
        (item: any) => dealElementDataObj?.[item]?.[0]?.value,
      );
      form.setFieldsValue({ stationList: checkedKeys });
    }
  };

  // 提醒设置弹框
  const handleSetReminders = async () => {
    const hasSave =
      buttonPermissions?.filter((item: any) => item.menuCode === 'reminderButtonV2')?.length > 0;
    if (!hasSave) {
      return message.info('请联系管理员获取相关权限');
    }
    const result: any = await SetRemindersModal.show({
      searchFormData,
      value,
      isEdit,
      getSearchFormData,
      marketId,
    });
    if (result.index === 1) {
      const values = form && form.getFieldsValue();
      const data = { ...value, ...values, ...result.data };
      setValue(data);
      form.setFieldsValue({ ...values, ...result.data });
      const reminderTypeData = REMINDER_TYPE_LIST.find(
        (item: any) => item.value === data?.reminderType,
      );
      const text =
        (data?.remindFlag === '1' && data?.reminderTime && data?.reminderTime.length > 0) ||
        reminderTypeData ||
        data?.reminderList
          ? `提醒设置：${
              data?.reminderTime && data?.reminderTime.length > 0
                ? data?.reminderTime
                    .map((item: any) => {
                      return CHECKTIME[String(item)]?.label;
                    })
                    .join(',')
                : '无'
            } / ${reminderTypeData ? reminderTypeData?.label : '无'} / 提醒对象(${
              data?.reminderList ? data?.reminderList?.length : 0
            }人)：${
              data?.reminderList && data?.reminderList?.length > 0
                ? data?.reminderList.map((item: any) => item.name).join(',')
                : '无'
            }`
          : '提醒设置';
      setWarnText(text);
    }
  };

  // 表单提交
  const onSubmit = () => {
    form &&
      form.validateFields().then(async (values) => {
        setIsLoading(true);
        const {
          calendarDate = undefined,
          reminderList = [],
          id = null,
          ...rest
        } = {
          ...value,
          ...values,
        };
        const pendingStartTime = moment(values?.pendingTime[0]).format('HH:mm:ss');
        const pendingEndTime = moment(values?.pendingTime[1]).format('HH:mm:ss');
        const params = {
          ...rest,
          pendingStartTime,
          pendingEndTime,
          createType: 0,
          calendarDate: moment(calendarDate).format('YYYY-MM-DD'),
          reminderList: reminderList?.map((item: any) => item.userId),
        };
        if (isEdit) {
          let res: any = {};
          res = await editPendingH({ ...params, id });
          if (res?.statusCode === HttpCode.SUCCESS) {
            setIsLoading(false);
            message.info('保存成功！');
            setVisible(false);
            setFlashKey(`${moment().valueOf()}edit`);
            setMonthflashKey(moment().valueOf());
            onPress({ index: 1 });
          } else {
            message.info(res?.message || '保存失败！');
            setIsLoading(false);
          }
        } else {
          let res: any = null;
          res = await savePendingH(params);
          if (res?.statusCode === HttpCode.SUCCESS) {
            message.info('新建待办成功！');
            setIsLoading(false);
            setFlashKey(moment().valueOf());
            setMonthflashKey(moment().valueOf());
            setVisible(false);
            onPress({ index: 1 });
          } else {
            message.info(res?.message || '新建待办失败！');
            setIsLoading(false);
          }
        }
      });
  };

  const footerRender = () => [
    <Button key="dtest1" onClick={_onCancel} loading={isLoading}>
      取消
    </Button>,
    <Button key="dtest2" type="primary" onClick={onSubmit} loading={isLoading}>
      提交
    </Button>,
  ];

  return (
    <Modal
      width="60%"
      className={styles.modal}
      centered
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <span className={styles.title}>{isEdit ? '编辑待办' : '新建待办'}</span>
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <div className={styles.container}>
        <Form
          className={styles.form}
          form={form}
          name="todo"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          colon={false}
          labelAlign="left"
          autoComplete="off"
          requiredMark={false}
        >
          <Form.Item
            name="transactionArrange"
            label="待办内容"
            rules={[
              { required: true, message: '请填写待办内容' },
              { max: 50, message: '待办内容不可超过50个字符' },
            ]}
          >
            <Input.TextArea placeholder="请填写待办内容" maxLength={50} />
          </Form.Item>
          <Form.Item
            name="calendarDate"
            label="待办日期"
            rules={[{ required: true, message: '请选择待办日期' }]}
          >
            <ShowDatePicker format="YYYYMMDD" placeholder="请选择时间" />
          </Form.Item>
          <Form.Item
            name="pendingTime"
            label="待办时间"
            rules={[{ required: true, message: '请选择待办时间' }]}
          >
            <ShowTimePicker
              type="rangePicker"
              format="HHmm"
              placeholder={['开始时间', '结束时间']}
            />
          </Form.Item>
          <Form.Item
            name="stationList"
            label="交易单元"
            rules={[{ required: true, message: '请选择交易单元' }]}
          >
            <Select
              placeholder={'交易单元'}
              showArrow={true}
              open={false}
              onClick={handelSelectDealElement}
              mode="multiple"
              maxTagTextLength={1}
              maxTagCount={1}
              options={dealElementOptions as any[]}
            />
          </Form.Item>
          {/*<div*/}
          {/*  className={warnText !== '提醒设置' ? styles.warn : styles.otherWarn}*/}
          {/*  onClick={handleSetReminders}*/}
          {/*>*/}
          {/*  <BellOutlined className={styles.logo} />*/}
          {/*  <Tooltip*/}
          {/*    placement={'topLeft'}*/}
          {/*    overlayClassName={styles.overlayClassName}*/}
          {/*    title={<div>{warnText}</div>}*/}
          {/*  >*/}
          {/*    {warnText}*/}
          {/*  </Tooltip>*/}
          {/*</div>*/}
        </Form>
      </div>
    </Modal>
  );
};

class TodoModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <TodoModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new TodoModal();
